#!/command/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Start nginx service
# ==============================================================================

set -e

bashio::log.info "Merging options & variables for template"
# shellcheck disable=SC2046
JSON_CONF=$(jq --arg port $(bashio::core.port) \
    '({options: .}) + ({variables: {port: $port}})' \
    /data/options.json)
bashio::log.info "Generating nginx.conf from template in /etc/nginx/nginx.conf.gtpl"
# shellcheck disable=SC2086
echo $JSON_CONF | tempio \
    -template /etc/nginx/nginx.conf.gtpl \
    -out /etc/nginx.conf

DHPARAMS_PATH=/data/dhparams.pem

CLOUDFLARE_CONF=/data/cloudflare.conf

# Generate dhparams
if ! bashio::fs.file_exists "${DHPARAMS_PATH}"; then
    bashio::log.info  "Generating dhparams (this will take some time)..."
    openssl dhparam -dsaparam -out "$DHPARAMS_PATH" 4096 > /dev/null
fi

if bashio::config.true 'cloudflare'; then
    # Generate cloudflare.conf
    if ! bashio::fs.file_exists "${CLOUDFLARE_CONF}"; then
        bashio::log.info "Creating 'cloudflare.conf' for real visitor IP address..."
        echo "# Cloudflare IP addresses" > $CLOUDFLARE_CONF;
        echo "" >> $CLOUDFLARE_CONF;

        echo "# - IPv4" >> $CLOUDFLARE_CONF;
        for i in $(curl https://www.cloudflare.com/ips-v4); do
            echo "set_real_ip_from ${i};" >> $CLOUDFLARE_CONF;
        done

        echo "" >> $CLOUDFLARE_CONF;
        echo "# - IPv6" >> $CLOUDFLARE_CONF;
        for i in $(curl https://www.cloudflare.com/ips-v6); do
            echo "set_real_ip_from ${i};" >> $CLOUDFLARE_CONF;
        done

        echo "" >> $CLOUDFLARE_CONF;
        echo "real_ip_header CF-Connecting-IP;" >> $CLOUDFLARE_CONF;
    fi
fi

# start server
bashio::log.info "Running nginx..."
stat "/ssl/$(bashio::config 'certfile')" -c %y > /tmp/certificate_timestamp
exec nginx -c /etc/nginx.conf < /dev/null
